import {UniStorage} from "@/util/uniUtils";
import LocalStorageConstant from "@/constant/LocalStorageConstant"
import {postActionSimple, putActionSimple} from "@/util/api";
import UserApi from "@/api/UserApi";
import DictApi from "@/api/DictApi";

const user = {
    state: {
        token: UniStorage.get(LocalStorageConstant.TOKEN) || '',
        userInfo: UniStorage.get(LocalStorageConstant.USER_INFO) || {},
        roles: UniStorage.get(LocalStorageConstant.ROLES) || []
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
            UniStorage.set(LocalStorageConstant.TOKEN, token)
        },
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
            UniStorage.set(LocalStorageConstant.USER_INFO, userInfo)
        },
        SET_ROLES(state, roles) {
            state.roles = roles
            UniStorage.set(LocalStorageConstant.ROLES, roles)
        }
    },
    actions: {
        async Login({commit}, userInfo) {
            let result = await postActionSimple(UserApi.url.login, userInfo)
            let {token, loginUser, roles} = result
            commit('SET_TOKEN', token)
            commit('SET_USER_INFO', loginUser)
            commit('SET_ROLES', roles)

            //获取数据字典
            await DictApi.getDict()
        },
        async Logout({commit}) {
            try {
                return await postActionSimple(UserApi.url.logout)
            } finally {
                commit('SET_TOKEN', null)
                commit('SET_USER_INFO', {})
            }
        },
        async ChangePassword({commit}, userInfo) {
            let result = await putActionSimple(UserApi.url.changePassword, userInfo)
            console.log("result", result)
            return result
        },
        async getUserInfo({commit}) {
            let userInfo = await UserApi.getUserInfo();
            console.log("userInfo",userInfo)
            commit('SET_USER_INFO', userInfo)
            commit('SET_ROLES', userInfo.roles)
            return userInfo
        }
    }
}
export default user
